package com.atguigu.tingshu.payment.api;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.tingshu.payment.service.WxPayService;
import com.github.wxpay.sdk.WXPayUtil;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@Tag(name = "微信支付接口")
@RestController
@RequestMapping("/api/payment/wxPay")
@Slf4j
public class WxPayApiController {

    @Autowired
    private WxPayService wxPayService;

    /**
     * 模拟微信返回结果
     * 微信支付结果的通知地址：被动获取支付结果
     * @return
     */
    @SneakyThrows
    @RequestMapping("/wxNotifyAddress")
    public String wxNotifyAddress(HttpServletRequest request,
                                  String orderNo,
                                  String routingKey){
//        // 获取 微信支付结果 的数据流
//        ServletInputStream inputStream = request.getInputStream();
//        // 声明输出流
//        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//        // 声明缓冲流
//        byte[] buffer = new byte[1024];
//        // 初始化数据长度
//        int len = 0 ;
//        // 循环读取数据
//        while((len = inputStream.read(buffer)) != -1){
//            // 写数据
//            outputStream.write(buffer,0,len);
//        }
//        // 获取数据byte数组
//        byte[] bytes = outputStream.toByteArray();
//        // 转换为字符串
//        String xmlString = new String(bytes);
//        // 转换为Map数据
//        Map<String, String> result = WXPayUtil.xmlToMap(xmlString);
//        System.out.println(JSONObject.toJSONString(result));
//        result.put("out_trade_no",orderNo);
//        // 关闭流
//        inputStream.close();
//        outputStream.flush();
//        outputStream.close();
        String resultString = "{\"transaction_id\":\"4200002203202405150243319278\",\"nonce_str\":\"9b5bd0d0267245b2847998b4de22de98\",\"bank_type\":\"OTHERS\",\"openid\":\"oHwsHuDel-4NF_VksirEEu04Q4xI\",\"sign\":\"E289998A4A6591F25CBD4371ED6A2E7F\",\"fee_type\":\"CNY\",\"mch_id\":\"1558950191\",\"cash_fee\":\"1\",\"out_trade_no\":\"VipOrderNo1790013521652748000\",\"appid\":\"wx74862e0dfcf69954\",\"total_fee\":\"1\",\"trade_type\":\"NATIVE\",\"result_code\":\"SUCCESS\",\"attach\":\"{\\\"exchange\\\":\\\"payment_info_exchange\\\",\\\"routingKey\\\":\\\"payment.order\\\"}\",\"time_end\":\"20240515164444\",\"is_subscribe\":\"N\",\"return_code\":\"SUCCESS\"}";
        Map result = JSONObject.parseObject(resultString, Map.class);
        result.put("out_trade_no",orderNo);
//        String attachString = JSONObject.toJSONString(result.get("attach"));
//        attachString = "{\"exchange\":\"payment_info_exchange\",\"routingKey\":\"payment.order\"}"
//         修改本地流水记录
        Map<String, String> attach = new HashMap<>();
        attach.put("exchange", "payment_info_exchange");
        attach.put("routingKey", routingKey);
        result.put("attach", JSONObject.toJSONString(attach));
        CompletableFuture.runAsync(()->{
           wxPayService.updatePaymentInfo(result);
        });
        // 返回结果初始化
        Map<String,String> resultMap = new HashMap<>();
        // 包装返回数据
        resultMap.put("return_code","SUCCESS");
        resultMap.put("return_msg","OK");
        // 返回
        return WXPayUtil.mapToXml(resultMap);
    }


}
